<?php

declare(strict_types=1);

namespace App\Model\PssModel;

use App\Model\BaseModel\BasePssModel;
use App\Service\Code\Normal;
use App\Service\OrderService\OrderQueryService\QueryGoodsMicService;
use App\Service\CommodityService\BbcBestGoodsService;

class ShopGoodsGroupList extends BasePssModel
{
    public $table = 'shop_goods_group_list';
    
    /**
     * 获取商品分组列表分页数据 
     */
    public function getGoodsGroupPageList( $param = [] ) 
    {
        $body   = $param['body'];
        $binfo  = $param['binfo'];
        if( empty($body['group_id']) ) {
            return Normal::returnCode(Normal::FAIL,"except param group_id");
        }
        $page       = isset($body['page']) ? $body['page'] : 1 ;
        $limit      = isset($body['limit']) ? $body['limit'] : 10 ;
        $group_id   = $body['group_id'];
        $groupInfo  = ShopGoodsGroup::instance()->info(['id'=>$group_id]); 
        if (empty($groupInfo) ) {
            return Normal::returnCode(Normal::FAIL,"当前商品分组信息不存在");
        }

        $columns = ShopSeckill::instance()->getSecKillQueryColumns();
        $columns = array_merge($columns, ['sorts', 'cd']);
        $list = $this->where('group_id',$group_id)->orderBy('sorts','desc')->orderBy("cd","desc")->paginate($limit, $columns, 'page', $page)->toArray();
        if( !empty($list['data']) )
        {
            $goodsIds = array_column($list['data'],'goods_id');
            $CopWhere = [
                'bid'       => 0,
                'skuids'    => $goodsIds
            ];
            $res = BbcBestGoodsService::instance()->getDispatchGoodsList($CopWhere);
            if( $res['code'] != Normal::SUC ) {
                return $res;
            }
            $res = QueryGoodsMicService::instance()->getGoodsListByCaculationAction($binfo,$res['data']);
            $goodsById = array_column($list['data'], null, 'goods_id');
            $newGoodsData = $res['data'];
            foreach ($newGoodsData as &$item){
                if(isset($goodsById[$item['goods_id']])){
                    $item['sorts'] = $goodsById[$item['goods_id']]['sorts'];
                    $item['cd']    = $goodsById[$item['goods_id']]['cd'];
                }else{
                    $item['sorts'] = 0;
                    $item['cd']    = 0;
                }
            }
            //重新排序
            array_multisort(array_column($newGoodsData,'sorts'),SORT_DESC,array_column($newGoodsData,'cd'),SORT_DESC,$newGoodsData);
            $list['data'] = $newGoodsData;
        }
        $list['group_goods_name'] = $groupInfo['group_name'];
        return Normal::returnCode(Normal::SUC,"获取成功",$list);
    }
}
